package jpaperwork.web;

import java.util.List;
import java.util.ListIterator;
import java.util.ArrayList;
import java.util.Iterator;

public class TemplateParser {
    public final List<Fragment> fragments;

    public TemplateParser(String pattern) {
        List<Character> list = new ArrayList<Character>();
        for (int i = 0; i< pattern.length(); i++){
            list.add(pattern.charAt(i));
        }
        fragments = parse(list.listIterator());
    }

    private List<Fragment> parse(ListIterator<Character> characterIterator) {
        List<Fragment> fragments = new ArrayList<Fragment>();


        while (characterIterator.hasNext()) {
            final Character nextChar = characterIterator.next();

            if (nextChar.equals('{')) {
                fragments.add(parsePlaceHolder(characterIterator));
            } else {

                characterIterator.previous();
                fragments.add(parseText(characterIterator));
            }
        }
        return fragments;
    }

    private TextFragment parseText(ListIterator<Character> characterIterator) {
        StringBuffer buffer = new StringBuffer();

        while (characterIterator.hasNext()) {
            final Character nextChar = characterIterator.next();
            if (nextChar.equals('{')) {
                characterIterator.previous();

                return new TextFragment(buffer.toString());

            }
            buffer.append(nextChar);
        }
        return new TextFragment(buffer.toString());
    }

    private PlaceholderFragment parsePlaceHolder(Iterator<Character> characterIterator) {
        StringBuffer buffer = new StringBuffer();

        while (characterIterator.hasNext()) {
            final Character nextChar = characterIterator.next();
            if (nextChar.equals('}')) {

                return new PlaceholderFragment(buffer.toString());

            }
            buffer.append(nextChar);
        }
        throw new RuntimeException("Was Expecting '}'");
    }

}